# coding: utf-8

from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_user, logout_user, login_required, current_user
from flask_principal import Permission, RoleNeed
from flask_login import LoginManager
from auth.forms import LoginForm, RegisterForm
from db.models import db, User, SysRole, SysUserRole
from config import app

auth_blueprint = Blueprint('auth', __name__)


@auth_blueprint.route('/home', methods=['GET'])
@login_required
def home():
    print("*"*100)
    print(current_user)
    return render_template('home.html', username=current_user.username)

@login_required
@auth_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user.is_active == 0:
            flash('用户已禁用, 请联系系统管理员')
            return redirect(url_for('auth.login'))
        if user.is_delete == 1:
            flash('用户已被删除，且无法使用该用户名注册, 请联系系统管理员')
            return redirect(url_for('auth.login'))
        
        if user is not None and user.password == form.password.data:
            login_user(user)
            return redirect(url_for('auth.home'))
        flash('用户名或密码有误!')
    return render_template('auth/login.html', form=form, current_user=current_user)

@auth_blueprint.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        if form.password.data != form.confirm_password.data:
            flash('两次密码不一致')
            return render_template('register.html', form=form)
        existing_user = User.query.filter_by(username=form.username.data).first()
        if existing_user is None:
            # 创建用户
            user = User(username=form.username.data)
            user.password = form.password.data
            user.is_active = 1
            db.session.add(user)

            # 创建普通用户角色
            common_role = SysRole.query.filter_by(role_key='ROLE_USER').first()
            common_user_role = SysUserRole(
                user_id=user.id, 
                username=user.username, 
                role_id=common_role.id, 
                role_key=common_role.role_key)
            db.session.add(common_user_role)

            db.session.commit()
            login_user(user)
            flash('注册成功！', 'success')
            return redirect(url_for('auth.home'))
        flash('该用户名已被注册，请尝试其他用户名。', 'danger')
    return render_template('auth/register.html', form=form)

@auth_blueprint.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.login'))